<script setup lang="ts">
import { reactive, ref, watch, computed } from 'vue'
import { type FormRules } from 'element-plus'
import { hasSpaceWithStartAndEnd } from '@/utils/validate'
import { getExhibitionHall } from '@/api/interface/content/introduce'

interface Props {
  data?: Record<string, any> | never | null
  status?: any
  type: any
}

const props = withDefaults(defineProps<Props>(), {
  data: null,
  status: 'add',
  type: ''
})

const disabled = computed(() => {
  return props.status === 'read'
})

const formRef = ref()

const form = reactive<Record<string, any>>({})

const rules = reactive<FormRules>({
  exhibitionHallName: [
    { required: true, message: '标题不能为空!', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value) {
          if (hasSpaceWithStartAndEnd(value)) {
            callback(new Error('标题首尾不能有空格!'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  content: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!form.news || form.news === '<p><br></p>' || form.news === '<p></p>') {
          callback(new Error('内容不能为空!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

const loading = ref(false)

const customEditorRef = ref()

const defaultContent = ref('[]')

const editorKey = ref(`${new Date().getTime()}`)

watch(defaultContent, () => {
  editorKey.value = `${new Date().getTime()}`
})

const initForm = () => {
  if (props.data) {
    // 编辑
    loading.value = true
    getExhibitionHall({
      id: props.data.id
    })
      .then((res: any) => {
        Object.keys(res).forEach((key: string) => {
          if (res![key] || res![key] === 0) {
            if (key === 'content') {
              defaultContent.value = res![key]
              form[key] = res![key]
            } else if (key === 'news') {
              newsHtml.value = customEditorRef.value.formatImage(res[key])
            } else {
              form[key] = res![key]
            }
          }
        })
      })
      .finally(() => {
        loading.value = false
      })
  }
}
initForm()

const handleContentChange = (content: string, html: string) => {
  form.content = content
  form.news = html
}

const formatForm = () => {
  const result: Record<string, any> = {}
  Object.keys(form).forEach((key: string) => {
    if (key === 'news') {
      result[key] = customEditorRef.value.formatImage(form[key])
    } else {
      result[key] = form[key]
    }
  })
  return result
}

const submitForm = () => {
  return new Promise<any>((resolve) => {
    formRef.value.validate((valid: boolean) => {
      let res: any = null
      if (valid) {
        res = formatForm()
      }
      resolve(res)
    })
  })
}

const newsHtml = ref('')

defineExpose({
  submitForm
})
</script>

<template>
  <div v-loading="loading" class="form-wrapper">
    <el-form ref="formRef" :model="form" :rules="rules" label-position="top" label-width="120px">
      <el-form-item label="标题：" prop="exhibitionHallName">
        <el-input v-model="form.exhibitionHallName" type="text" placeholder="请输入标题" maxlength="20" :disabled="disabled" />
      </el-form-item>
      <el-form-item :key="editorKey" label="内容：" prop="content">
        <CustomEditor v-show="!disabled" ref="customEditorRef" :default-content="defaultContent" @content-change="handleContentChange"></CustomEditor>
        <div v-show="disabled" v-dompurify-html="newsHtml" style="width: 100%; word-wrap: break-word"></div>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.form-wrapper {
  padding-left: 10px;
}
</style>
